<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮 -->
      <template #toolbar>
        <div v-for="(item, index) in butData" :key="index">
          <a-popconfirm
            v-if="item.btnKey === 'btnCancel'"
            title="是否确认取消关联？"
            ok-text="是"
            cancel-text="否"
            placement="bottom"
            @confirm="handleCancelBasInv()"
          >
            <a-button :key="index" :type="item.btnType" v-auth="item.auth">
              <Icon v-if="item.icon" :icon="item.icon" /> {{ t(item.title) }}
            </a-button>
          </a-popconfirm>
          <a-button v-else :key="index" :type="item.btnType" @click="item.do" v-auth="item.auth">
            <Icon v-if="item.icon" :icon="item.icon" /> {{ t(item.title) }}
          </a-button>
        </div>
      </template>
      <!-- 表格插槽 -->
      <template #firstColumn="{ record }">
        <a @click="handleForm({ clsCode: record.clsCode, invCode: record.invCode })">
          {{ record.clsCode }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <FormImport @register="registerImportModal" @success="handleSuccess" />
    <ListSelect
      ref="listSelectRef"
      selectType="basInvSelect"
      :checkbox="true"
      @select="handleUserSelect"
      :selectList="selectListRef"
      v-show="false"
    />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsShopProductShopProductClsInvList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref, watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { router } from '/@/router';
  import { useGlobSetting } from '/@/hooks/setting';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadByUrl } from '/@/utils/file/download';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, useTable, ActionItem } from '/@/components/Table';
  import { listSet, customListData } from '/@/api/test/testData';
  import { tabConfigData, schemasData } from '/@/utils/custom';
  import { useModal } from '/@/components/Modal';
  import { useDrawer } from '/@/components/Drawer';
  import { ListSelect } from '/@/components/ListSelect';
  import InputForm from './form.vue';
  import FormImport from './formImport.vue';
  import { batchSaveInv, cancelInv } from '/@/api/shop/product/shopProductClsInv';

  const { t } = useI18n('sys.role');
  const { showMessage } = useMessage();

  const listSelectRef = ref<any>(null);

  const props = defineProps({
    treeCode: String,
    treeName: String,
  });

  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const selectListRef = ref<Recordable[]>([]);

  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 4, md: 6 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setProps, getForm, getSelectRows }] = useTable({
    //actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
  });

  onMounted(async () => {
    const res = await listSet({ viewCode: 'shop_cls_inv_list001' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮
    butData.value.forEach((item) => {
      if (item.btnKey === 'btnAdd') {
        item.do = () => handleBasInv();
      }
      if (item.btnKey === 'btnExport') {
        item.do = () => handleExport();
      }
      if (item.btnKey === 'btnImport') {
        item.do = () => handleImport();
      }
      if (item.btnKey === 'btnCancel') {
        item.do = () => handleCancelBasInv();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        params.url = listTabConfig.value.api;
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        clsCode: props.treeCode,
        'proCls.name': props.treeName,
      });
      reload();
    },
  );

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/shop/product/shopProductClsInv/exportData',
      target: '_self',
    });
  }

  const [registerImportModal, { openModal: importModal }] = useModal();

  function handleImport() {
    importModal(true, {});
  }

  async function handleDelete(record: Recordable) {
    const res = await shopProductClsInvDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  // 关联产品
  async function handleBasInv() {
    if (props.treeCode) {
      listSelectRef.value.openSelectModal();
    } else {
      showMessage(t('产品系列不能为空，请先选择产品系列！'));
    }
  }

  // 取消关联
  async function handleCancelBasInv() {
    if (!props.treeCode) {
      showMessage(t('请先选择产品系列！'));
      return;
    }
    if (getSelectRows().length) {
      var selIds = ref('');
      var clsCode = ref('');
      getSelectRows().forEach((item) => {
        clsCode.value += item.clsCode + ',';
        selIds.value += item.invCode + ',';
      });
      const res = await cancelInv({ selIds: selIds.value, clsCode: clsCode.value });
      showMessage(res.message);
      handleSuccess();
    } else {
      showMessage(t('请选择至少一行数据！'));
    }
  }

  async function handleUserSelect(values: Recordable[]) {
    if (values.length == 0) {
      showMessage(t('请先选择产品系列！'));
      return;
    }
    const params = {
      clsCode: props.treeCode,
      invCode: values.map((e) => e.cinvcode).join(','),
    };
    const res = await batchSaveInv(params);
    showMessage(res.message);
    handleSuccess();
    listSelectRef.value.setSelectList = [];
  }

  function handleSuccess() {
    reload();
  }
</script>
<style></style>
